import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: '/api', // 使用相对路径，配合vite代理
  timeout: 600000, // 增加超时时间到10分钟，适应大文件上传
  headers: {
    'Content-Type': 'application/json'
  },
  withCredentials: true, // 允许跨域携带cookie
  // 处理大整数问题：将ID转换为字符串以避免精度丢失
  transformResponse: [function (data) {
    try {
      // 解析JSON字符串，然后递归处理大整数
      const parsedData = JSON.parse(data, (key, value) => {
        // 检查是否为接近或超过JavaScript安全整数范围的数字
        if (typeof value === 'number' && Math.abs(value) > 1e15) {
          return String(value); // 转换为字符串以保持精度
        }
        return value;
      });
      return parsedData;
    } catch (e) {
      return data;
    }
  }]
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// 获取视频列表（分页查询）
export const getVideoList = (params) => {
  return api.post('/video/findPage', params)
}

// 上传视频（同步）
export const uploadVideo = (formData) => {
  return api.post('/video/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

// 上传视频（异步）
export const asyncUploadVideo = (formData, onUploadProgress) => {
  return api.post('/video/upload/async', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    onUploadProgress: onUploadProgress // 添加上传进度回调
  })
}

// 查询上传任务状态
export const getUploadStatus = (taskId) => {
  return api.get(`/video/upload/status/${taskId}`)
}

// 删除单个视频
export const deleteVideo = (id) => {
  return api.delete(`/video/delete/${id}`)
}

// 批量删除视频
export const batchDeleteVideos = (videoIds) => {
  return api.delete('/video/delete', {
    data: videoIds
  })
}

// 修改视频信息
export const updateVideoInfo = (updateData) => {
  return api.put('/video/update', updateData)
}

// 视频分页查询
export const findVideoPage = (pageDTO) => {
  return api.post('/video/findPage', pageDTO)
}

export const isUse = (data)=>{
  return api.put('/video/isUse', {
    id: data.id,
    status: data.status
  })
}

// 根据ID获取视频详情
export const getVideoInfoById = (id) => {
  return api.get('/video/getVideoInfoById', {
    params: {
      id: id
    }
  })
}

// 获取浏览量前六的视频
export const getTopVideos = () => {
  return api.get('/video/getTop')
}